import config from './config'

const formatTime = (time, format = 'yyyy-mm-dd HH:MM') => {
  let date;
  if (time.toString().length == 13) {
    date = new Date(time);
  } else {
    date = new Date(time * 1000);
  }
  let year = date.getFullYear()
  let month = formatNumber(date.getMonth() + 1)
  let day = formatNumber(date.getDate())
  let hour = formatNumber(date.getHours())
  let minute = formatNumber(date.getMinutes())
  let second = formatNumber(date.getSeconds())

  format = format.replace('yyyy', year)
  format = format.replace('mm', month)
  format = format.replace('dd', day)
  format = format.replace('HH', hour)
  format = format.replace('MM', minute)
  format = format.replace('ss', second)

  return format
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

const cdn = (url) => {
  if (!url) {
    return ''
  }
  if (typeof url === 'string') {
    if ((/^(http|https):\/\/.+/.test(url))) {
      return url
    } else {
      return config.cdn + url
    }
  } else {
    let arr = []
    for (let i = 0; i < url.length; i++) {
      if ((/^(http|https):\/\/.+/.test(url[i]))) {
        arr.push(url[i])
      } else {
        arr.push(config.cdn + url[i])
      }
    }
    return arr
  }
}
const skip = (url, events = {}, success) => {
  wx.navigateTo({
    url,
    events,
    success
  })
}

const authSkip = (url, events = {}) => {
  if (wx.getStorageSync('token')) {
    wx.navigateTo({
      url,
      events
    })
  } else {
    // #if MP
    wx.navigateTo({
      url: '/service/login/login',
      events
    })
    // #elif NATIVE
    wx.navigateTo({
      url: '/service/applogin/login',
      events
    })
    // #endif
  }
}

const back = (delta = 1) => {
  wx.navigateBack({
    delta: delta
  })
}

const toast = (msg, time = 2000) => {
  wx.showToast({
    title: msg,
    icon: 'none',
    duration: time
  })
}

const previewImage = (arr, index = 0) => {
  wx.previewImage({
    urls: cdn(arr),
    current: cdn(arr)[index]
  })
}


module.exports = {
  formatTime: formatTime,
  cdn: cdn,
  skip: skip,
  authSkip: authSkip,
  back: back,
  toast: toast,
  previewImage: previewImage
}